package com.device1.springbootdevice1.controller;

import com.device1.springbootdevice1.entity.Devices;
import com.device1.springbootdevice1.repository.DevicesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/devices")
//实现跨域注解
//origin="*"代表所有域名都可访问
//maxAge飞行前响应的缓存持续时间的最大年龄，简单来说就是Cookie的有效期 单位为秒
//若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失
@CrossOrigin(origins = "*",maxAge = 3600)
public class DevicesHandler {
    @Autowired
    private DevicesRepository devicesRepository;

    @GetMapping("/findAll")
    public List<Devices> findAll(){
        return devicesRepository.findAll();
    }

    @GetMapping("/findAll/{page}/{size}")
    public Page<Devices> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return devicesRepository.findAll(pageable);
    }
    @PostMapping("/save")//应该是postMapping
    public String save(@RequestBody Devices devices){
        Devices result=devicesRepository.save(devices);
        if(result!=null){
            return "success";
        }else{
            return "error";
        }
    }
    @GetMapping("/findById/{id}")
    public boolean findById(@PathVariable("id") String id){
        //devicesRepository.findById(id)是一个Optional类。
        if(devicesRepository.findById(id).isPresent()){
            return true;
        }
        return false;
    }
    @PutMapping("/update")
    public String update(@RequestBody Devices devices){
        Devices result = devicesRepository.save(devices);
        if( result!=null){
            return "success";
        }else{
            return "error";
        }
    }
    @DeleteMapping("/deleteById/{id}")//开始写成deleteId,前端用的deleteById，所以出现跨域错误
    public void deleteById(@PathVariable("id") String id){
        devicesRepository.deleteById(id);
    }
}
